﻿using Himp.Outpatient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EventBus.Distributed;

namespace Himp.Outpatient
{
    /// <summary>
    /// 锁定号源服务
    /// </summary>
    public class OtpSchdRecLockService : OutpatientAppService
    {
        private readonly IRepository<OtpSchdRec, Guid> _otpSchdRecRepository;
        private readonly IRepository<OtpSchdRecDetl, Guid> _otpSchdRecDetlRepository;
        private readonly IDistributedEventBus _distributedEventBus;

        public OtpSchdRecLockService(IRepository<OtpSchdRec, Guid> otpSchdRecRepository
            , IRepository<OtpSchdRecDetl, Guid> otpSchdRecDetlRepository
            , IDistributedEventBus distributedEventBus)
        {
            _otpSchdRecRepository = otpSchdRecRepository;
            _otpSchdRecDetlRepository = otpSchdRecDetlRepository;
            _distributedEventBus = distributedEventBus;
        }

        /// <summary>
        /// 锁定号源
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<OtpSchdRecLockDto> Post(OtpSchdRecLockCreateDto input)
        {
            OtpSchdRecLockDto otpSchdRecLockDto = new OtpSchdRecLockDto();
            var otpSchdRec = await _otpSchdRecRepository.GetAsync(input.OtpSchdRecId);
            otpSchdRec.OverCnt = otpSchdRec.OverCnt - 1;

            if (input.OtpSchdRecDetlId != null)
            {
                var otpSchdRecDetl = otpSchdRec.OtpSchdRecDetls.First(o => o.Id == input.OtpSchdRecDetlId);
                otpSchdRecDetl.OverCnt = otpSchdRecDetl.OverCnt - 1;
            }

            OtpSchdRecLockCreatedEto eto = new OtpSchdRecLockCreatedEto();
            eto.MdtrtSn = input.MdtrtSn;
            eto.OtpSchdRecId = input.OtpSchdRecId;
            eto.OtpSchdRecDetlId = input.OtpSchdRecDetlId;
            await _distributedEventBus.PublishAsync(eto);

            return otpSchdRecLockDto;
        }
    }
}
